package com.ssl.basics.thread.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：
 *
 * @author shi_senlin
 * @create 2021/07/08 22:46
 */
public class NofifyThread {
    public static void main(String[] args) {
        Res res = new Res();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.incre();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.decre();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.incre();
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.decre();
            }
        }, "DD").start();
    }

    static class Res {
        private int number = 0;
        private Lock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();

        public void incre() {
            lock.lock();
            try {
                while (0 != number) {
                    condition.await();
                }
                number++;
                System.out.println(Thread.currentThread().getName() + "  " + number);
                condition.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void decre() {
            lock.lock();
            try {
                while (1 != number) {
                    condition.await();
                }
                number--;
                System.out.println(Thread.currentThread().getName() + "  " + number);
                condition.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
